﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Diagnostics;
using System.Net;
using System.IO;
using EricUtility;
using System.Threading;
using EricUtility.Networking.Gathering;
using EbayQueryExpertLib;
using EbayQueryExpertLib.EbayFinding;
using EbayQueryExpertLib.Entities;

namespace EbayQueryExpert
{
    public partial class SimpleSearchForm : Form
    {
        int curPage = 0;
        int maxPage = 0;
        int totalentries = 0;
        int epp = 0;
        private Dictionary<int, List<EbaySearchItem>> m_Results = new Dictionary<int, List<EbaySearchItem>>();
        private string keywords;
        private Thread m_SearchTread;
        private SearchType m_SearchType;
        public SimpleSearchForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void LoadSearch(object pageO)
        {
            BeforeAndAfter(false);
            curPage = (int)pageO;
            if (m_Results.ContainsKey(curPage))
            {
                foreach (EbaySearchItem item in m_Results[curPage])
                {
                    AddToListBox(item);
                    SayInfo("Results loaded ! Showing results " + (((curPage - 1) * epp) + 1) + " - " + (curPage * epp) + " out of " + totalentries + " results");
                }
            }
            else
            {
                m_Results.Add(curPage, new List<EbaySearchItem>());
                SayInfo("Requesting Ebay ...");
                using (FindingServicePortTypeClient client = new FindingServicePortTypeClient())
                {
                    FindItemsAdvancedResponse response = m_SearchType == SearchType.ByKeyword ? EbayEndPoint.AdvancedSearch(curPage, 100, new ManualSearchQuery(keywords)) : EbayEndPoint.AdvancedSearch(curPage, 100, new ManualSearchQuery(null, keywords.Split(',')));
                    if (response.searchResult == null || response.searchResult.item == null)
                    {
                        totalentries = 0;
                        epp = 0;
                        curPage = 0;
                        maxPage = 0;
                    }
                    else
                    {

                        SayInfo("Loading Page " + response.paginationOutput.pageNumber + " of " + response.paginationOutput.totalPages + " (" + response.searchResult.item.Length + " / " + response.paginationOutput.totalEntries + " results)");
                        SetMaxProgress(response.searchResult.item.Length);
                        foreach (SearchItem item in response.searchResult.item)
                        {
                            EbaySearchItem it = new EbaySearchItem(item);
                            it.LoadIfNeeded();
                            AddToListBox(it);
                            m_Results[curPage].Add(it);
                            IncProgress();
                        }
                        curPage = response.paginationOutput.pageNumber;
                        maxPage = response.paginationOutput.totalPages;
                        totalentries = response.paginationOutput.totalEntries;
                        epp = response.paginationOutput.entriesPerPage;
                    }
                    SayInfo("Results loaded ! Showing results " + (((curPage-1) * epp) + 1) + " - " + (curPage * epp) + " out of " + totalentries + " results");
           
                } 
                             
            }
            BeforeAndAfter(true);
            m_SearchTread = null;
        }
        private delegate void EbaySearchItemHandler(EbaySearchItem it);
        private void AddToListBox(EbaySearchItem it)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new EbaySearchItemHandler(AddToListBox), new object[] { it });
                return;
            }
            listBox1.Items.Add(it);
        }
        private delegate string StringReturnHandler();
        private string GetKeyword()
        {
            if (this.InvokeRequired)
            {
                return((string)this.Invoke(new StringReturnHandler(GetKeyword), new object[] { }));
            }
            return txtSearchKeyword.Text;
        }
        private void SayInfo(String msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new StringHandler(SayInfo), new object[] { msg });
                return;
            }
            lblInfo.Text = msg;
        }
        private void BeforeAndAfter(bool atEnd)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new BooleanHandler(BeforeAndAfter), new object[] { atEnd });
                return;
            }
            btnSearchKeywords.Enabled = atEnd;
            label2.Text = curPage + " / " + maxPage;
            btnNextPage.Enabled = atEnd && curPage < maxPage;
            btnPrevPage.Enabled = atEnd && curPage > 1;
        }
        private void SetMaxProgress(int max)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new IntHandler(SetMaxProgress), new object[] { max });
                return;
            }
            progressBar1.Maximum = max;
            progressBar1.Step = 1;
            progressBar1.Value = 0;
        }
        private void IncProgress()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new EmptyHandler(IncProgress), new object[] {});
                return;
            }
            progressBar1.Value++;
        }
        private void SimpleSearchForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_SearchTread != null)
            {
                m_SearchTread.Abort();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtSearchKeyword.Text))
            {
                m_SearchType = SearchType.ByKeyword;
                listBox1.Items.Clear();
                m_Results.Clear();
                keywords = txtSearchKeyword.Text;
                m_SearchTread = new Thread(new ParameterizedThreadStart(LoadSearch));
                m_SearchTread.Start(1);
            }
        }

        private void btnPrevPage_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            m_SearchTread = new Thread(new ParameterizedThreadStart(LoadSearch));
            m_SearchTread.Start(curPage-1);
        }

        private void btnNextPage_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            m_SearchTread = new Thread(new ParameterizedThreadStart(LoadSearch));
            m_SearchTread.Start(curPage+1);
        }

        private void btnSearchCat_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtSearchCat.Text))
            {
                m_SearchType = SearchType.ByCategory;
                listBox1.Items.Clear();
                m_Results.Clear();
                keywords = txtSearchCat.Text;
                m_SearchTread = new Thread(new ParameterizedThreadStart(LoadSearch));
                m_SearchTread.Start(1);
            }
        }
    }

}